<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <SearchForm
      v-model="searchForm"
      :inline="true"
      label-width="80px"
      @search="handleSearch"
      @reset="handleReset"
    >
      <el-form-item label="敏感词">
        <el-input v-model="searchForm.word" placeholder="请输入敏感词" clearable />
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
          <el-option 
            v-for="category in categories" 
            :key="category" 
            :label="category" 
            :value="category" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="ACTIVE" />
          <el-option label="禁用" value="INACTIVE" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </SearchForm>
    
    <!-- 统计卡片 -->
    <div class="stats-container">
      <StatCard
        title="敏感词总数"
        :value="statistics.totalWords || 0"
        icon="Warning"
        type="primary"
      />
      <StatCard
        title="今日新增"
        :value="statistics.todayNewWords || 0"
        icon="Plus"
        type="success"
      />
      <StatCard
        title="今日拦截"
        :value="statistics.todayBlocked || 0"
        icon="CircleClose"
        type="danger"
      />
      <StatCard
        title="拦截率"
        :value="statistics.blockRate || 0"
        icon="DataLine"
        type="warning"
        suffix="%"
      />
    </div>
    
    <!-- 图表区域 -->
    <div class="chart-container">
      <div class="chart-row">
        <!-- 敏感词拦截趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">敏感词拦截趋势</div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="blockTrendChartRef"
              :options="blockTrendChartOptions"
              :loading="chartLoading"
              height="300px"
            />
          </div>
        </div>
        
        <!-- 敏感词分类分布 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">敏感词分类分布</div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="categoryChartRef"
              :options="categoryChartOptions"
              :loading="chartLoading"
              height="300px"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 敏感词表格 -->
    <Card title="敏感词列表">
      <template #extra>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增敏感词
        </el-button>
        <el-button type="success" @click="handleImport">
          <el-icon><Upload /></el-icon>
          导入
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <el-button @click="handleTest">
          <el-icon><Check /></el-icon>
          测试
        </el-button>
      </template>
      
      <CommonTable
        ref="tableRef"
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #status="{ row }">
          <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'danger'">
            {{ row.status === 'ACTIVE' ? '启用' : '禁用' }}
          </el-tag>
        </template>
        
        <template #category="{ row }">
          <el-tag type="info">{{ row.category }}</el-tag>
        </template>
        
        <template #action="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="primary" link @click="handleViewUsage(row)">
            <el-icon><View /></el-icon>
            使用记录
          </el-button>
          <el-button 
            type="primary" 
            link 
            @click="handleToggleStatus(row)"
          >
            <el-icon><Switch /></el-icon>
            {{ row.status === 'ACTIVE' ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </CommonTable>
    </Card>
    
    <!-- 敏感词表单对话框 -->
    <CommonDialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增敏感词' : '编辑敏感词'"
      width="600px"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="敏感词" prop="word">
          <el-input v-model="formData.word" placeholder="请输入敏感词" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
            <el-option 
              v-for="category in categories" 
              :key="category" 
              :label="category" 
              :value="category" 
            />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义分类" prop="customCategory" v-if="formData.category === 'custom'">
          <el-input v-model="formData.customCategory" placeholder="请输入自定义分类" />
        </el-form-item>
        <el-form-item label="替换词" prop="replaceWord">
          <el-input v-model="formData.replaceWord" placeholder="请输入替换词，留空则使用***替换" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select v-model="formData.level" placeholder="请选择级别" style="width: 100%">
            <el-option label="低" :value="1" />
            <el-option label="中" :value="2" />
            <el-option label="高" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="ACTIVE">启用</el-radio>
            <el-radio label="INACTIVE">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="formData.remark" 
            type="textarea" 
            placeholder="请输入备注" 
            :rows="3" 
          />
        </el-form-item>
      </el-form>
    </CommonDialog>
    
    <!-- 导入对话框 -->
    <CommonDialog
      v-model="importVisible"
      title="导入敏感词"
      width="500px"
      @confirm="handleImportSubmit"
      @cancel="handleCancelImport"
    >
      <el-form
        ref="importFormRef"
        :model="importForm"
        :rules="importFormRules"
        label-width="100px"
      >
        <el-form-item label="文件" prop="file">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            drag
            :auto-upload="false"
            :limit="1"
            accept=".txt,.csv"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传txt/csv文件，且每行一个敏感词
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="importForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option 
              v-for="category in categories" 
              :key="category" 
              :label="category" 
              :value="category" 
            />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义分类" prop="customCategory" v-if="importForm.category === 'custom'">
          <el-input v-model="importForm.customCategory" placeholder="请输入自定义分类" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select v-model="importForm.level" placeholder="请选择级别" style="width: 100%">
            <el-option label="低" :value="1" />
            <el-option label="中" :value="2" />
            <el-option label="高" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="importForm.status">
            <el-radio label="ACTIVE">启用</el-radio>
            <el-radio label="INACTIVE">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </CommonDialog>
    
    <!-- 测试对话框 -->
    <CommonDialog
      v-model="testVisible"
      title="敏感词测试"
      width="600px"
      :show-footer="false"
    >
      <el-form
        ref="testFormRef"
        :model="testForm"
        label-width="100px"
      >
        <el-form-item label="测试文本" prop="text">
          <el-input 
            v-model="testForm.text" 
            type="textarea" 
            placeholder="请输入要测试的文本" 
            :rows="5" 
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleTestSubmit" :loading="testLoading">
            测试
          </el-button>
          <el-button @click="handleResetTest">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div v-if="testResult.show" class="test-result">
        <div class="result-header">
          <span>测试结果</span>
          <el-tag :type="testResult.hasSensitiveWords ? 'danger' : 'success'">
            {{ testResult.hasSensitiveWords ? '包含敏感词' : '不包含敏感词' }}
          </el-tag>
        </div>
        
        <div v-if="testResult.hasSensitiveWords" class="result-content">
          <div class="result-item">
            <div class="result-label">原始文本：</div>
            <div class="result-value">{{ testResult.originalText }}</div>
          </div>
          <div class="result-item">
            <div class="result-label">处理后文本：</div>
            <div class="result-value">{{ testResult.processedText }}</div>
          </div>
          <div class="result-item">
            <div class="result-label">敏感词列表：</div>
            <div class="result-value">
              <el-tag 
                v-for="(word, index) in testResult.sensitiveWords" 
                :key="index" 
                type="danger" 
                style="margin-right: 5px;"
              >
                {{ word }}
              </el-tag>
            </div>
          </div>
        </div>
        
        <div v-else class="result-content">
          <div class="result-item">
            <div class="result-label">文本内容：</div>
            <div class="result-value">{{ testResult.originalText }}</div>
          </div>
        </div>
      </div>
    </CommonDialog>
    
    <!-- 使用记录对话框 -->
    <CommonDialog
      v-model="usageVisible"
      title="敏感词使用记录"
      width="1000px"
      :show-footer="false"
    >
      <div class="usage-container">
        <div class="usage-header">
          <div class="word-info">
            <span>敏感词: {{ currentWord.word }}</span>
            <span>分类: {{ currentWord.category }}</span>
            <span>级别: {{ getLevelLabel(currentWord.level) }}</span>
          </div>
          <div class="usage-actions">
            <el-button @click="refreshUsage" :loading="usageLoading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
        
        <CommonTable
          :data="usageRecords"
          :columns="usageColumns"
          :loading="usageLoading"
          :show-pagination="false"
          :max-height="400"
        >
          <template #action="{ row }">
            <el-button type="primary" link @click="handleViewUser(row)">
              <el-icon><User /></el-icon>
              查看用户
            </el-button>
          </template>
        </CommonTable>
      </div>
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getSensitiveWordList, 
  getSensitiveWordDetail, 
  createSensitiveWord, 
  updateSensitiveWord, 
  deleteSensitiveWord, 
  batchDeleteSensitiveWords, 
  updateSensitiveWordStatus, 
  getSensitiveWordStatistics, 
  getSensitiveWordCategories, 
  getSensitiveWordUsageRecords,
  checkSensitiveWords,
  importSensitiveWords,
  exportSensitiveWords
} from '@/api/sensitiveWord'
import { useTable } from '@/hooks/useTable'
import { useForm } from '@/hooks/useForm'
import { useDialog } from '@/hooks/useDialog'
import { downloadFile } from '@/utils'

// 表格列配置
const columns = [
  {
    type: 'selection',
    width: '55'
  },
  {
    prop: 'id',
    label: 'ID',
    width: '80'
  },
  {
    prop: 'word',
    label: '敏感词',
    minWidth: '120'
  },
  {
    prop: 'category',
    label: '分类',
    width: '120',
    slot: 'category'
  },
  {
    prop: 'replaceWord',
    label: '替换词',
    minWidth: '120'
  },
  {
    prop: 'level',
    label: '级别',
    width: '100'
  },
  {
    prop: 'status',
    label: '状态',
    width: '100',
    slot: 'status'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: '180',
    sortable: 'custom'
  },
  {
    prop: 'action',
    label: '操作',
    width: '280',
    slot: 'action',
    fixed: 'right'
  }
]

// 使用记录表格列配置
const usageColumns = [
  {
    prop: 'content',
    label: '内容',
    minWidth: '300'
  },
  {
    prop: 'username',
    label: '用户名',
    width: '120'
  },
  {
    prop: 'ip',
    label: 'IP地址',
    width: '120'
  },
  {
    prop: 'userAgent',
    label: '用户代理',
    minWidth: '200'
  },
  {
    prop: 'createTime',
    label: '使用时间',
    width: '180'
  },
  {
    prop: 'action',
    label: '操作',
    width: '100',
    slot: 'action',
    fixed: 'right'
  }
]

// 搜索表单
const searchForm = reactive({
  word: '',
  category: '',
  status: '',
  dateRange: []
})

// 统计数据
const statistics = reactive({
  totalWords: 0,
  todayNewWords: 0,
  todayBlocked: 0,
  blockRate: 0
})

// 图表相关
const blockTrendChartRef = ref(null)
const categoryChartRef = ref(null)
const chartLoading = ref(false)
const blockTrendChartOptions = ref({})
const categoryChartOptions = ref({})

// 表格相关
const {
  tableData,
  loading,
  pagination,
  selectedRows,
  loadData,
  handleSelectionChange,
  handleSortChange,
  handleSizeChange,
  handleCurrentChange
} = useTable(getSensitiveWordList, {
  defaultParams: searchForm,
  immediate: false
})

// 表单相关
const defaultFormData = {
  word: '',
  category: '',
  customCategory: '',
  replaceWord: '',
  level: 1,
  status: 'ACTIVE',
  remark: ''
}

const formRules = {
  word: [
    { required: true, message: '请输入敏感词', trigger: 'blur' },
    { min: 1, max: 50, message: '敏感词长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  customCategory: [
    { required: true, message: '请输入自定义分类', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择级别', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const {
  formData,
  formRef,
  submitting,
  resetForm,
  validateForm,
  submitForm
} = useForm(defaultFormData, handleSubmit, {
  resetAfterSubmit: false
})

// 导入表单相关
const importFormRules = {
  file: [
    { required: true, message: '请上传文件', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  customCategory: [
    { required: true, message: '请输入自定义分类', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择级别', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const {
  formData: importForm,
  formRef: importFormRef,
  submitting: importSubmitting,
  validateForm: validateImportForm,
  submitForm: submitImportForm
} = useForm({
  file: null,
  category: '',
  customCategory: '',
  level: 1,
  status: 'ACTIVE'
}, handleImportSubmit)

// 测试表单相关
const {
  formData: testForm,
  formRef: testFormRef
} = useForm({
  text: ''
})

// 对话框相关
const {
  visible: dialogVisible,
  showDialog,
  hideDialog
} = useDialog()

const {
  visible: importVisible,
  showDialog: showImportDialog,
  hideDialog: hideImportDialog
} = useDialog()

const {
  visible: testVisible,
  showDialog: showTestDialog,
  hideDialog: hideTestDialog
} = useDialog()

const {
  visible: usageVisible,
  showDialog: showUsageDialog,
  hideDialog: hideUsageDialog
} = useDialog()

// 其他变量
const tableRef = ref(null)
const uploadRef = ref(null)
const dialogType = ref('add')
const categories = ref([])
const currentWord = reactive({})
const usageRecords = ref([])
const usageLoading = ref(false)
const testLoading = ref(false)
const testResult = reactive({
  show: false,
  hasSensitiveWords: false,
  originalText: '',
  processedText: '',
  sensitiveWords: []
})

// 获取统计数据
const getStatisticsData = async () => {
  try {
    const response = await getSensitiveWordStatistics()
    if (response) {
      Object.assign(statistics, response)
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 获取敏感词分类列表
const getCategoriesData = async () => {
  try {
    const response = await getSensitiveWordCategories()
    if (response && response.data) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取敏感词分类列表失败', error)
  }
}

// 获取图表数据
const getChartData = async () => {
  try {
    chartLoading.value = true
    
    // 模拟获取敏感词拦截趋势数据
    const blockTrendData = {
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '拦截次数',
          type: 'line',
          smooth: true,
          data: [120, 132, 101, 134, 90, 230, 210],
          areaStyle: {
            color: 'rgba(245, 108, 108, 0.2)'
          },
          lineStyle: {
            color: '#f56c6c'
          }
        }
      ]
    }
    
    // 模拟获取敏感词分类分布数据
    const categoryData = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '敏感词分类分布',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 335, name: '政治敏感' },
            { value: 310, name: '色情低俗' },
            { value: 234, name: '暴力恐怖' },
            { value: 135, name: '赌博诈骗' },
            { value: 154, name: '其他' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    blockTrendChartOptions.value = blockTrendData
    categoryChartOptions.value = categoryData
  } catch (error) {
    console.error('获取图表数据失败', error)
  } finally {
    chartLoading.value = false
  }
}

// 获取级别标签
const getLevelLabel = (level) => {
  const labels = {
    1: '低',
    2: '中',
    3: '高'
  }
  return labels[level] || level
}

// 处理搜索
const handleSearch = () => {
  loadData({
    ...searchForm,
    startTime: searchForm.dateRange?.[0],
    endTime: searchForm.dateRange?.[1]
  })
}

// 处理重置
const handleReset = () => {
  Object.assign(searchForm, {
    word: '',
    category: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 处理新增
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  showDialog()
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    const response = await getSensitiveWordDetail(row.id)
    if (response) {
      dialogType.value = 'edit'
      Object.assign(formData, response)
      showDialog()
    }
  } catch (error) {
    console.error('获取敏感词详情失败', error)
  }
}

// 处理查看使用记录
const handleViewUsage = async (row) => {
  try {
    Object.assign(currentWord, row)
    usageRecords.value = []
    showUsageDialog()
    await loadUsageRecords(row.id)
  } catch (error) {
    console.error('加载使用记录失败', error)
  }
}

// 加载使用记录
const loadUsageRecords = async (wordId) => {
  try {
    usageLoading.value = true
    const response = await getSensitiveWordUsageRecords({ wordId })
    if (response && response.data) {
      usageRecords.value = response.data.records || response.data || []
    }
  } catch (error) {
    console.error('获取使用记录失败', error)
  } finally {
    usageLoading.value = false
  }
}

// 刷新使用记录
const refreshUsage = async () => {
  await loadUsageRecords(currentWord.id)
}

// 处理查看用户
const handleViewUser = (row) => {
  ElMessage.info('查看用户功能开发中')
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除敏感词 "${row.word}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteSensitiveWord(row.id)
      ElMessage.success('删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('删除失败', error)
    }
  }).catch(() => {})
}

// 处理批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的敏感词')
    return
  }
  
  const ids = selectedRows.value.map(row => row.id)
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${ids.length} 个敏感词吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await batchDeleteSensitiveWords(ids)
      ElMessage.success('批量删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('批量删除失败', error)
    }
  }).catch(() => {})
}

// 处理切换状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
  const statusText = newStatus === 'ACTIVE' ? '启用' : '禁用'
  
  ElMessageBox.confirm(
    `确定要${statusText}敏感词 "${row.word}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateSensitiveWordStatus(row.id, newStatus)
      ElMessage.success(`${statusText}成功`)
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error(`${statusText}失败`, error)
    }
  }).catch(() => {})
}

// 处理导入
const handleImport = () => {
  importForm.file = null
  importForm.category = ''
  importForm.customCategory = ''
  importForm.level = 1
  importForm.status = 'ACTIVE'
  showImportDialog()
}

// 处理文件变化
const handleFileChange = (file) => {
  importForm.file = file.raw
}

// 处理文件移除
const handleFileRemove = () => {
  importForm.file = null
}

// 处理导入提交
async function handleImportSubmit() {
  try {
    if (!importForm.file) {
      ElMessage.warning('请上传文件')
      return
    }
    
    const category = importForm.category === 'custom' ? importForm.customCategory : importForm.category
    
    await importSensitiveWords(importForm.file, {
      category,
      level: importForm.level,
      status: importForm.status
    })
    
    ElMessage.success('导入成功')
    hideImportDialog()
    loadData()
    getStatisticsData()
  } catch (error) {
    console.error('导入失败', error)
  }
}

// 处理取消导入
const handleCancelImport = () => {
  hideImportDialog()
}

// 处理导出
const handleExport = async () => {
  try {
    const response = await exportSensitiveWords(searchForm)
    const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
    downloadFile(URL.createObjectURL(blob), '敏感词列表.xlsx')
  } catch (error) {
    console.error('导出失败', error)
  }
}

// 处理测试
const handleTest = () => {
  testForm.text = ''
  testResult.show = false
  testResult.hasSensitiveWords = false
  testResult.originalText = ''
  testResult.processedText = ''
  testResult.sensitiveWords = []
  showTestDialog()
}

// 处理测试提交
const handleTestSubmit = async () => {
  if (!testForm.text) {
    ElMessage.warning('请输入测试文本')
    return
  }
  
  try {
    testLoading.value = true
    const response = await checkSensitiveWords(testForm.text)
    
    if (response) {
      testResult.show = true
      testResult.hasSensitiveWords = response.hasSensitiveWords
      testResult.originalText = response.originalText
      testResult.processedText = response.processedText
      testResult.sensitiveWords = response.sensitiveWords || []
    }
  } catch (error) {
    console.error('测试失败', error)
  } finally {
    testLoading.value = false
  }
}

// 处理重置测试
const handleResetTest = () => {
  testForm.text = ''
  testResult.show = false
  testResult.hasSensitiveWords = false
  testResult.originalText = ''
  testResult.processedText = ''
  testResult.sensitiveWords = []
}

// 处理表单提交
async function handleSubmit() {
  try {
    const category = formData.category === 'custom' ? formData.customCategory : formData.category
    
    const data = {
      ...formData,
      category
    }
    
    if (dialogType.value === 'add') {
      await createSensitiveWord(data)
      ElMessage.success('新增成功')
    } else {
      await updateSensitiveWord(formData.id, data)
      ElMessage.success('更新成功')
    }
    
    hideDialog()
    loadData()
    getStatisticsData()
  } catch (error) {
    console.error('提交失败', error)
  }
}

// 处理取消
const handleCancel = () => {
  hideDialog()
}

onMounted(() => {
  loadData()
  getStatisticsData()
  getCategoriesData()
  getChartData()
})
</script>

<style lang="scss" scoped>
.app-container {
  .stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .chart-container {
    margin-bottom: 20px;
    
    .chart-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
      gap: 20px;
      
      .chart-card {
        background: var(--el-bg-color-overlay);
        border-radius: var(--el-border-radius-base);
        box-shadow: var(--el-box-shadow-lighter);
        padding: 20px;
        
        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          
          .chart-title {
            font-size: 16px;
            font-weight: bold;
            color: var(--el-text-color-primary);
          }
        }
        
        .chart-content {
          height: 300px;
        }
      }
    }
  }
  
  .test-result {
    margin-top: 20px;
    padding: 16px;
    border-radius: var(--el-border-radius-base);
    background-color: var(--el-fill-color-lighter);
    
    .result-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      span {
        font-size: 16px;
        font-weight: bold;
        color: var(--el-text-color-primary);
      }
    }
    
    .result-content {
      .result-item {
        margin-bottom: 12px;
        
        .result-label {
          font-size: 14px;
          color: var(--el-text-color-regular);
          margin-bottom: 4px;
        }
        
        .result-value {
          font-size: 14px;
          color: var(--el-text-color-primary);
          word-break: break-word;
        }
      }
    }
  }
  
  .usage-container {
    .usage-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      margin-bottom: 16px;
      
      .word-info {
        display: flex;
        gap: 16px;
        
        span {
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
      }
    }
  }
}
</style>